<template>
  <div class="main">
    <div class="common-layout">
      <el-container>
        <el-main>
          <LineItem class="type-title">
            <template #header-slot>
              <div class="title-type-slot">热门分类</div>
            </template>
            <template #main>
              <TypeItem
                v-for="(info, index) in typeInfo"
                :key="index"
                :info="info"
                @click="goToSearch(info.searchName)"></TypeItem>
            </template>
          </LineItem>
          <el-divider />
          <LineItem v-for="info in typeInfo" id="title">
            <template #header-slot>
              <div class="title-type-slot">— {{ info.name }} —</div>
            </template>
            <template #main>
              <GoodItem v-for="i in info.goods" :key="i" :item="i"></GoodItem>
              <el-empty v-if="info.goods.length == 0" description="暂无商品" />
            </template>
          </LineItem>
          <el-divider />
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script setup>
import GoodItem from '@/components/GoodsItem.vue'
import LineItem from '@/components/LineItem.vue'
import TypeItem from '@/components/TypeItem.vue'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getType, searchGoodsInfo } from '@/api/goods'
import { useRouter } from 'vue-router'

const route = useRoute()

const router = useRouter()

const typeInfo = ref([]) // 分类数组

// 分类表示
const typeId = {
  appliances: 1,
  technology: 2,
  sport: 3,
  food: 4
}

// 请求分类
const getTypeFromId = async () => {
  const type = route.params.type // 获取分类名
  const res = (await getType(typeId[type])).data
  res.data.forEach(async (item) => {
    // 搜索商品
    const goodsInfo = (await searchGoodsInfo(item.searchName, '综合')).data.data

    typeInfo.value.push({
      name: item.typeDetailName,
      url: new URL(item.src, import.meta.url).href,
      searchName: item.searchName,
      goods: goodsInfo
    })
  })
}

getTypeFromId()

// 监听路由变化
watch(
  () => route.params.type,
  () => {
    typeInfo.value = []
    getTypeFromId()
  },
  { deep: true }
)

// 跳转到搜索页
const goToSearch = (searchname) => {
  router.push({
    path: '/search',
    query: {
      searchname
    }
  })
}
</script>

<style scoped>
.el-header,
.el-main {
  background-color: white;
}

.el-header {
  height: 450px;
  margin-bottom: 20px;
  padding-top: 20px;
}
</style>
